from typing import List


class TreeNode:
    def __init__(self, val):
        self.val = val
        self.left = self.right = None


class ModeInBST:
    def __init__(self, root):
        self.root = root
        self.max = 0
        self.count = 0
        self.pre = None
        self.result = []

    def __call__(self, *args, **kwargs):
        self._helper(self.root)
        return self.result

    def _helper(self, node):
        # base
        if not node:
            return
        # left
        self._helper(node.left)

        # should the current node be put into the result?
        if self.pre and self.pre.val == node.val:
            self.count += 1
        else:
            self.count = 1

        if self.count > self.max:
            self.result.clear()
            self.result.append(node.val)
        elif self.count == self.max:
            self.result.append(node.val)

        self.pre = node

        # right
        self._helper(node.right)

def buildTree(input: List[int]) -> TreeNode:
    nodes = [TreeNode(x) for x in input]
    for i in range(1, len(input)):
        if input[i] is None:
            continue
        parent = (i + 1) // 2 - 1
        if i % 2 == 1:
            nodes[parent].left = nodes[i]
        else:
            nodes[parent].right = nodes[i]
    return nodes[0]
root = buildTree([1,None,2,2])
mode = ModeInBST(root)
mode()

print(mode.result)
